package org.alvin.switchserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.alvin.switchserver.ui.models.ServerNodeTableModel;

import java.beans.PropertyChangeSupport;

public class MultiServerForwarding {

    private Channel channel;

    private final int port;

    private final ServerNodeTableModel serverNodeTableModel;

    private final PropertyChangeSupport uiEventBus;

    public MultiServerForwarding(int port , ServerNodeTableModel serverNodeTableModel , PropertyChangeSupport uiEventBus) {
        this.port = port;
        this.serverNodeTableModel = serverNodeTableModel;
        this.uiEventBus = uiEventBus;
    }

    /**
     * 启动服务
     */
    public void start() {
        new Thread(() -> {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup(20);

            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {

                                socketChannel.pipeline()
                                        .addLast(new PrintInputNettyMegHandler(uiEventBus))
                                        .addLast(new MultiForwardingHandler(serverNodeTableModel,uiEventBus));
                            }
                        })
                        .option(ChannelOption.SO_BACKLOG, 128)
                        .childOption(ChannelOption.SO_KEEPALIVE, true);
                ChannelFuture f = b.bind(port).sync();
                System.out.println("=====启动完成=====");
                channel = f.channel();
                uiEventBus.firePropertyChange("serverStatusChange",false,"Running");
                channel.closeFuture().sync();
            } catch (Exception t) {
                t.printStackTrace();
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }
        }).start();
    }

    /**
     * 停止服务
     */
    public void stop() {
        if (channel.isOpen()) {
            channel.close();
            uiEventBus.firePropertyChange("serverStatusChange",false,"Stopped");
            System.out.println("=====停止完成=====");
        }
    }

    public boolean isOpen(){
        return channel != null && channel.isOpen();
    }


}